package com.ccl.keyassistant.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Switch;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.ccl.keyassistant.R;
import com.ccl.keyassistant.adapter.LocalRecycleAdapter;
import com.ccl.keyassistant.adapter.RecycleViewDivider;
import com.ccl.keyassistant.entity.LocalFile;
import com.ccl.keyassistant.utils.EncryptUtil;
import com.ccl.keyassistant.utils.FileUtil;
import com.ccl.keyassistant.utils.L;
import com.ccl.keyassistant.utils.StaticClass;
import com.ccl.keyassistant.view.CustomDialog;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


public class LocalFragment extends Fragment {

    private View mLocalFragment;
    private RecyclerView mRecycleView;
    private File mCurrentPath;
    private TextView mPath;
    private LocalRecycleAdapter mAdapter;
    private ArrayList<LocalFile> mLocalFile;
    private ArrayList<String> mFileList = new ArrayList<>();
    private static Context mContext;
    //    private TextView mEncrypt;
//    private TextView mDecrypt;
    //姿态观察者，用于处理屏幕触摸行为的
    private GestureDetectorCompat mGestureDetectorCompat;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case StaticClass.ENCRYPT_START:
                    L.i("ENCRYPT_START");
                    text_info.setText("正在加密");
                    dialog_load.show();
                    break;
                case StaticClass.ENCRYPT_END:
                    L.i("ENCRYPT_END");
                    dialog_load.dismiss();
                    ArrayList<LocalFile> fileList = FileUtil.getFileList(mCurrentPath);
                    update(fileList);
                    break;
                case StaticClass.DECRYPT_START:
                    L.i("DECRYPT_START");
                    text_info.setText("正在解密");
                    dialog_load.show();
                    break;
                case StaticClass.DECRYPT_EDN:
                    L.i("DECRYPT_EDN");
                    if (dialog_load != null) {
                        dialog_load.dismiss();
                    }
                    ArrayList<LocalFile> fileList2 = FileUtil.getFileList(mCurrentPath);
                    update(fileList2);
                    break;
                default:
                    break;
            }
        }
    };
    private static CustomDialog dialog_load;
    private static TextView text_info;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mLocalFragment = inflater.inflate(R.layout.fragment_local, container, false);
        mContext = getContext();
        initView();
        initData();
        return mLocalFragment;
    }

    private void initView() {
        mRecycleView = (RecyclerView) mLocalFragment.findViewById(R.id.rlv_sd_card);
//        添加自定义分割线：可自定义分割线drawable
//        mRecycleView.addItemDecoration(new RecycleViewDivider(
//                getContext(), LinearLayoutManager.VERTICAL, R.drawable.divider_mileage));
//        添加默认分割线：高度为2px，颜色为灰色
        mRecycleView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL));
//        添加自定义分割线：可自定义分割线高度和颜色
//        mRecycleView.addItemDecoration(new RecycleViewDivider(
//                getContext(), LinearLayoutManager.VERTICAL, 10, getResources().getColor(R.color.divide_gray_color)));
        //设置布局管理器
        mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        mPath = mLocalFragment.findViewById(R.id.tv_path);
//        mEncrypt = mLocalFragment.findViewById(R.id.tv_encrypt);
//        mDecrypt = mLocalFragment.findViewById(R.id.tv_decrypt);
        dialog_load = new CustomDialog(mContext, R.layout.custom_dialog_load);
        text_info = dialog_load.getWindow().findViewById(R.id.custom_load_text);
    }

    private void initData() {
        File root = Environment.getExternalStorageDirectory();
        mCurrentPath = root;
        mLocalFile = FileUtil.getFileList(root);
        setCurrentPath(root);
        //设置数据适配器
        mAdapter = new LocalRecycleAdapter(getContext(), mLocalFile);
        mRecycleView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new LocalRecycleAdapter.ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LocalFile localFile = mLocalFile.get(position);
                if (localFile != null && localFile.isDirectory()) {
                    mCurrentPath = new File(localFile.getFilePath());
                    setCurrentPath(mCurrentPath);
                    //此处不可以直接返回，要保持mAdapter地址不变，不然notifyDataSetChanged不起作用
                    ArrayList<LocalFile> fileList = FileUtil.getFileList(mCurrentPath);
                    update(fileList);
                } else {
                    //点击的是文件
                    LocalFile localFile1 = mLocalFile.get(position);
                    if (localFile1 != null) {
                        String filePath = localFile.getFilePath();
                        if (mFileList.contains(filePath)) {
                            mFileList.remove(filePath);
                        } else {
                            mFileList.add(filePath);
                        }
                    }

                }
            }
        });
        //触摸行为捕获
        mGestureDetectorCompat = new GestureDetectorCompat(mRecycleView.getContext(),
                new MyGestureListener());
        mRecycleView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent e) {
                mGestureDetectorCompat.onTouchEvent(e);
            }


            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
                mGestureDetectorCompat.onTouchEvent(e);
                return false;
            }
        });
    }

    private void setCurrentPath(File file) {
        if (file != null && file.isDirectory()) {
            mPath.setText(file.getAbsolutePath());
        }
    }

    private void update(ArrayList<LocalFile> list) {
        if (list == null) {
            return;
        }
        mLocalFile.clear();
        mLocalFile.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        //长按
        @Override
        public void onLongPress(MotionEvent e) {
            String type = null;
            AlertDialog.Builder alert = new AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
            alert.setTitle("提示");
            alert.setMessage("请选择处理方式");
            alert.setPositiveButton("加密", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //加密文件
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File file = null;
                            for (String string : mFileList) {
                                file = new File(string);
                                if (!file.isDirectory()) {
                                    mHandler.sendEmptyMessage(StaticClass.ENCRYPT_START);
                                    EncryptUtil.encrypt(getContext(), file);
                                }
                            }
                            mHandler.sendEmptyMessage(StaticClass.ENCRYPT_END);
                            mFileList.clear();
                        }
                    }).start();
                }
            });

            alert.setNegativeButton("解密", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //解密文件
                            File file = null;
                            for (String string : mFileList) {
                                file = new File(string);
                                if (!file.isDirectory()) {
                                    mHandler.sendEmptyMessage(StaticClass.DECRYPT_START);
                                    EncryptUtil.decrypt(getContext(), file);
                                }
                            }
                            mHandler.sendEmptyMessage(StaticClass.DECRYPT_EDN);
                            mFileList.clear();
                        }
                    }).start();
                }
            });

            alert.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            });
            alert.create().show();
            if (mFileList == null && mFileList.size() <= 0) {
                return;
            }
            mAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        ArrayList<LocalFile> fileList = FileUtil.getFileList(mCurrentPath);
        update(fileList);
    }
}
